//  检查项目选择
//  ZhuanXiangZhiBiaoViewController.m
//  yilutongxing
//
//  Created by Robin-Pc on 2017/5/8.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "ZhuanXiangZhiBiaoViewController.h"
#import "YZEUIButtonChoose.h"
#import "QMUIFloatLayoutView.h"
#import "functions.h"
#import "CommonDefine.h"
#import "DataUtils.h"
#import "RPSpecialIndicatorToBechoosen.h"

#define URL_GetSIName @"/api/special-indicators/list"

@interface ZhuanXiangZhiBiaoViewController ()
@property(nonatomic, strong)UIScrollView *container;
@property(nonatomic, strong)NSMutableArray *layoutArr;
@property(nonatomic, strong)NSMutableArray *btnArr;
@property (strong,nonatomic) NSMutableArray *choosenList;
@property(strong,nonatomic) NSMutableArray *indicatorsArr;
//@property(strong,nonatomic) NSMutableDictionary *subIndicatorDic;

@property(strong,nonatomic) NSMutableArray *btnGroupArr;//按钮组

@end

@implementation ZhuanXiangZhiBiaoViewController

- (NSMutableArray *)getLayoutArr{
    if (!_layoutArr) {
        _layoutArr = [[NSMutableArray alloc]init];
    }
    return _layoutArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"检查项目";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"返回"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBackAction)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(addAction)];
    
    //数据初始化
    self.layoutArr = [[NSMutableArray alloc]init];
    self.btnArr = [[NSMutableArray alloc]init];
    
    BOOL ret = [DataUtils fileIfExists:SINAME_CACHE];//本地是否有缓存
    if (!ret) {
        //网络请求指标字典
        [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_GetSIName] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
            BOOL ret = [DataUtils saveDataToPlist:SINAME_CACHE data:responseObject];//缓存到本地
            NSAssert(ret, @"缓存%@失败！", SINAME_CACHE);
            self.indicatorsArr = [RPSpecialIndicatorToBechoosen mj_objectArrayWithKeyValuesArrayAdd:responseObject];
            
            [self initUI];
            [self settingFrames];
        }];
    }
    else {
        NSArray *ia = [[NSMutableArray alloc]initWithContentsOfFile:[[DataUtils getDocumentsPath] stringByAppendingPathComponent:SINAME_CACHE]];
        self.indicatorsArr = [RPSpecialIndicatorToBechoosen mj_objectArrayWithKeyValuesArrayAdd:ia];
        //_subIndicatorDic = [[NSMutableDictionary alloc]initWithContentsOfFile:[[DataUtils getDocumentsPath] stringByAppendingPathComponent:SUBPROINDEX]];
        if ([DataUtils fileIfExists:CHOOSEN_PROINDEX]) {
            _choosenList = [[NSMutableArray alloc]initWithContentsOfFile:[[DataUtils getDocumentsPath] stringByAppendingPathComponent:CHOOSEN_PROINDEX]];
        }
        
        [self initUI];
        [self settingFrames];
    }
}

/*
 *后台请求并整理、缓存数据
 */
+ (void)requestIndicatorData:(getIndicatorDataDidFinishedBlock)callback{
    dispatch_async(GLOBAL_BG_QUEUE, ^{
        [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_GetSpecialIndicatorsDic]
                                          parameters:nil
                                            delegate:self
                                          requestTag:1
                                        successBlock:^(id responseObject)
         {
             //指标数据
             NSMutableArray *proindexArr = [NSMutableArray array];
             NSMutableDictionary *proindexSubDic = [NSMutableDictionary dictionary];
             NSMutableDictionary *proindexDic = [NSMutableDictionary dictionary];
             NSMutableDictionary *subProindexNameDic = [NSMutableDictionary dictionary];
             for (NSDictionary *item in responseObject) {
                 NSString *tableName = item[@"tableName"];
                 id flag = [proindexDic objectForKey:tableName];
                 if (!flag) {
                     [proindexDic setObject:@1 forKey:tableName];
                     [proindexArr addObject:tableName];
                     NSMutableArray *tmpArr = [NSMutableArray array];
                     [tmpArr addObject:item];
                     [proindexSubDic setObject:tmpArr forKey:tableName];
                 }
                 else {
                     NSMutableArray *arrRef = [proindexSubDic objectForKey:tableName];
                     [arrRef addObject:item];
                 }
                 subProindexNameDic[item[@"propertyName"]] = item;
             }
             BOOL ret = [DataUtils saveDataToPlist:PROINDEXARR data:proindexArr];//缓存到本地
             NSAssert(ret, @"缓存%@失败！", PROINDEXARR);
             ret = [DataUtils saveDataToPlist:SUBPROINDEX data:proindexSubDic];
             NSAssert(ret, @"缓存%@失败！", SUBPROINDEX);
             [DataUtils saveDataToPlist:SUBPROINDEXDIC data:subProindexNameDic];
             if (callback) {
                 callback(proindexArr, proindexSubDic);
             }
         }];
    });
}

+ (void)requestIndicatorNameForCache{
    BOOL ret = [DataUtils fileIfExists:SINAME_CACHE];//本地是否有缓存
    if (!ret) {
        //网络请求指标字典
        [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_GetSIName] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
            BOOL ret = [DataUtils saveDataToPlist:SINAME_CACHE data:responseObject];//缓存到本地
            NSAssert(ret, @"缓存%@失败！", SINAME_CACHE);
        }];
    }
}

//初始化UI
- (void)initUI{
    //滚动容器
    self.container = [[UIScrollView alloc]initWithFrame:CGRectMake(0,
                                                                   0,
                                                                   SCREEN_WIDTH,
                                                                   SCREEN_HEIGHT - 10
                                                                   )];
    [self.view addSubview:_container];
    //构造UI元素
    UIEdgeInsets padbox = UIEdgeInsetsMake(0, 0, 8, 6);
    for (RPSpecialIndicatorToBechoosen *indicator in _indicatorsArr.objectEnumerator) {
        if(indicator.show){
            NSArray *sub_arr = indicator.specialIndicatorsDTOs;
            UIView *titleBar = [[UIView alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH-10, 20)];
            //指标类目名称
            UILabel *cn = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
            cn.text = indicator.name;
            [titleBar addSubview:cn];
            //全选按钮
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-100, 0, 100, 20)];
            [btn setTitle:@"全选" forState:UIControlStateNormal];
            [btn setTitleColor:Bluecolor forState:UIControlStateNormal];
            [titleBar addSubview:btn];
            btn.tag = [self.btnGroupArr count];
            [btn addTarget:self action:@selector(chooseAllAction:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.container addSubview:titleBar];
            [self.layoutArr addObject:titleBar];
            
            //flow layout
            NSMutableArray *subBtnArr = [NSMutableArray array];
            QMUIFloatLayoutView *box = [[QMUIFloatLayoutView alloc]init];
            box.itemMargins = padbox;
            [self.container addSubview:box];
            [self.layoutArr addObject:box];
            for (RPSpecialIndicatorToBechoosen *subi in sub_arr.objectEnumerator) {
                if (subi.show) {
                    YZEUIButtonChoose *btn = [[YZEUIButtonChoose alloc]initWithTitle:subi.name];
                    [btn addTarget:self action:@selector(onTap:) forControlEvents:UIControlEventTouchUpInside];
                    if (_choosenList && [_choosenList containsObject:subi.name]) {
                        btn.selected = YES;
                    }
                    [subBtnArr addObject:btn];
                    [box addSubview:btn];
                    [self.btnArr addObject:btn];
                }
            }
            
            [self.btnGroupArr addObject:subBtnArr];
        
            CGFloat contentWidth = SCREEN_WIDTH - 32;
            CGSize floatLayoutViewSize = [box sizeThatFits:CGSizeMake(contentWidth, CGFLOAT_MAX)];
            box.frame = CGRectMake(16, cn.y + cn.height + 15, contentWidth, floatLayoutViewSize.height);
        }
    }
}

//更新布局
-(void)settingFrames{
    for (int i=2; i<self.layoutArr.count; i++) {//从2开始，略过前两个元素
        if (i%2!=0) {
            QMUIFloatLayoutView *lv = self.layoutArr[i-1];
            UILabel *cv = self.layoutArr[i];
            cv.x += 6;
            cv.y = lv.y + lv.height + 15;
        }
        else {
            UILabel *lv = self.layoutArr[i-1];
            QMUIFloatLayoutView *cv = self.layoutArr[i];
            cv.y = lv.y + lv.height + 15;;
        }
    }
    QMUIFloatLayoutView *last = _layoutArr.lastObject;
    CGSize size = self.container.size;
    size.height = last.y + last.height + 10;
    self.container.contentSize = size;
    
    [self.container scrollsToTop];
}
//"保存"按钮响应
-(void)addAction{
    if (!_choosenList) {
        _choosenList = [[NSMutableArray alloc]init];
    }
    else
        [_choosenList removeAllObjects];
    
    UIButton *btn;
    for (int i=0; i<_btnArr.count; i++) {
        btn = _btnArr[i];
        if (btn.isSelected) {
            [_choosenList addObject:btn.titleLabel.text];
        }
    }
    //存入plist
    BOOL ret = [DataUtils saveDataToPlist:CHOOSEN_PROINDEX data:_choosenList];
    NSAssert(ret, @"已选指标写入plist失败！");
    
    if ([self.delegate respondsToSelector:@selector(backChoosenIndicators:)]) {
        [self.delegate backChoosenIndicators:_choosenList];
    }
    
    [self leftBackAction];
}

-(void)leftBackAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)onTap:(YZEUIButtonChoose *)sender{
    sender.selected = !sender.selected;
}

-(void)chooseAllAction:(UIButton*)sender {
    if (sender.tag >= [self.btnGroupArr count]) {
        return;
    }
    BOOL isAll = NO;
    if ([sender.titleLabel.text isEqualToString:@"全选"]) {
        [sender setTitle:@"取消全选" forState:UIControlStateNormal];
        isAll = YES;
    }
    else {
        [sender setTitle:@"全选" forState:UIControlStateNormal];
    }
    
    NSArray *subBtnArr = self.btnGroupArr[sender.tag];
    NSEnumerator *en = [subBtnArr objectEnumerator];
    YZEUIButtonChoose *btn = nil;
    while (btn = [en nextObject]) {
        btn.selected = isAll;
    }
}

#pragma mark 业务逻辑

#pragma mark 数据配置
- (NSMutableArray *)btnGroupArr{
    if (!_btnGroupArr) {
        _btnGroupArr = [NSMutableArray array];
    }
    return _btnGroupArr;
}

@end
